<template>
  <el-container>
    <el-header>
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="bg-purple">
            <el-link href="/user/#/" :underline="false">
              <img src="../assets/logo.png" alt="logo" class="logo" />
            </el-link>
            <span>文章发布</span>
            <el-link href="/user/#/" :underline="false" class="ml-20">
              <el-button type="primary">返回首页</el-button>
            </el-link>
          </div>
        </el-col>
        <el-col :span="6" :offset="10">
          <div class="bg-purple">
            <el-link
              style="float: right; margin-right: 80px; color: #fff"
              :underline="false"
              type="primary"
              @click="loginout"
              >退出</el-link
            >
          </div>
        </el-col>
      </el-row>
    </el-header>
    <el-main>
      <el-form :model="dataForm" label-width="120px">
        <el-form-item label="标题" class="color_withe">
          <el-input v-model="dataForm.title" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="来源">
              <el-input v-model="dataForm.source" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="作者">
              <el-input v-model="dataForm.writer" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="标题缩略图">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleImagSuccess"
            :before-upload="beforeImgUpload"
            name="upload"
          >
            <img
              v-if="dataForm.titlepic"
              :src="domain + dataForm.titlepic"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="关键词">
          <el-input v-model="dataForm.keywords" />
        </el-form-item>
        <el-form-item label="摘要">
          <el-input v-model="dataForm.summary" type="textarea" :rows="4" />
        </el-form-item>
        <el-form-item label="正文:">
          <div class="editor-view">
            <!-- 编辑器 -->
            <div id="editor"></div>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">Save</el-button>
          <el-button>Cancel</el-button>
        </el-form-item>
      </el-form>
    </el-main>
    <el-footer>
      <div class="text-center">
        <span>版权所有：xxxxxxxxxxxxx Copyright ©1995-2023</span>
        <a
          href="http://beian.miit.gov.cn/"
          target="_blank"
          style="margin-left: 40px; color: #709eef"
          >京ICP备xxxxxxxxx号-x</a
        >
      </div>
    </el-footer>
  </el-container>
</template>
<script>
import Editor from "@ckeditor/ckeditor5-build-classic";
import "@ckeditor/ckeditor5-build-classic/build/translations/zh-cn";
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

// 设置编辑器对象
let myEditor = undefined;

export default {
  name: "",
  data() {
    return {
      dataForm: {
        id: 0,
        cid: 2, // 新闻资讯
        title: "",
        writer: "",
        source: "",
        titlepic: "",
        keywords: "",
        summary: "",
        content: "",
      },
      uploadUrl: "",
      // 编辑内容
      editorData: "<p>Content of the editor</p>",
      // 编辑器配置
      editorConfig: {
        // 配置语言
        language: "zh-cn",
        // 功能栏
        // toolbar: {
        //   items: ['Bold', 'Italic', 'Link' ...]
        // }
        // 更多的配置....
      },
    };
  },
  components: { Editor, Plus, ElMessage },
  computed: {},
  beforeMount() {},
  mounted() {
    this.init();
  },
  methods: {
    init() {
      // 是否登录
      let token = window.sessionStorage.getItem("token")
      
      if (!token) {
        this.$router.push({ path: "/login" })
      }
      // 拼接图片上传需要的 token
      this.uploadUrl = "/api/member/uploadImage?token=" + token

      let id = this.$route.params.id || 0;

      if (id !== 0) {
        this.$http.get("/member/articleinfo", { id: id }, (res) => {
          if (res && res.code === 0) {
            // console.log(res)
            let info = res.data
            this.dataForm.id = info.id
            this.dataForm.cid = info.cid
            this.dataForm.title = info.title
            this.dataForm.writer = info.writer
            this.dataForm.source = info.source
            this.dataForm.titlepic = info.titlepic
            this.dataForm.keywords = info.keywords
            this.dataForm.summary = info.summary
            this.dataForm.content = info.content
          }
          this.createEditor(); // 初始化编辑器
        });
      } else {
        this.createEditor(); // 初始化编辑器
      }
    },
    // 初始化编辑器
    createEditor() {
      Editor.create(document.querySelector("#editor"), this.editorConfig)
        .then((editor) => {
          // console.log("创建成功");
          // 监听内容变化
          // editor.model.document.on("change:data", (e) => {
          //   // 输出当前内容
          //   console.log(editor.getData(), e);
          // });
          // 设置内容
          // console.log(this.dataForm.content);
          editor.setData(this.dataForm.content);
          // 记录编辑器对象
          myEditor = editor;
        })
        .catch((error) => {
          // console.log("创建失败");
          console.log(error);
        });
    },
    // 标题图上传成功
    handleImagSuccess(res, uploadFile) {
      // console.log(res);
      if (res.uploaded === 1) {
        this.dataForm.titlepic = res.url
      } else {
        ElMessage.error(res.msg)
      }
    },
    // 上传前检测
    beforeImgUpload(rawFile) {
      if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
        ElMessage.error("Avatar picture must be JPG or PNG format!");
        return false;
      } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error("Avatar picture size can not exceed 2MB!");
        return false;
      }
      return true;
    },
    // 保存文章
    onSubmit() {
      this.dataForm.content = myEditor.getData();
      // console.log(this.dataForm.content);
      this.$http.post("/member/articlesave", this.dataForm, (res) => {
        if (res && res.code === 0) {
          this.$message({
            message: res.msg,
            type: "success",
            duration: 1500,
          });
          this.$router.push({ path: "/" })
        } else {
          this.$message({
            message: res.msg,
            type: "error",
          });
        }
      });
    },
    // 登出
    loginout() {
      window.sessionStorage.clear();
      this.$router.push({ path: "/login" });
    },
  },
  watch: {},
};
</script>
<style scoped lang="scss">
.el-header {
  line-height: 60px;
  background-color: #f1acac;
  .logo {
    width: 60px;
    height: 60px;
  }
}
.el-main {
  width: 1300px;
  margin: 0 auto;
  .editor-view {
    width: 100%;
  }
  .content {
    margin-top: 30px;
    .title {
      font-size: 22px;
      line-height: 30px;
      font-weight: bold;
      padding-left: 8px;
      box-sizing: border-box;
    }
    .el-menu-demo {
      border-bottom: none;
    }
  }
}
.el-footer {
  color: #fff;
  line-height: 60px;
  margin-top: 60px;
  background-color: #393b3f;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.ck-editor__editable_inline {
  height: 400px;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>